package com.test.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Server {
    static Selector selector;

    static ByteBuffer readBf = ByteBuffer.allocate(1024);
    static ByteBuffer writeBf = ByteBuffer.allocate(1024);

    public static void main(String[] args) throws Exception {
        selector = Selector.open();

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        String host = "localhost";
        int port = 8081;
        ssc.bind(new InetSocketAddress(host, port));
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("准备监听" + host + ":" + port);


        while (true) {
            int select = selector.select(5000000);
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while (it.hasNext()) {
                SelectionKey key = it.next();
                if (key.isAcceptable()) {
                    SocketChannel accept = ((ServerSocketChannel) key.channel()).accept();
                    accept.configureBlocking(false);
                    accept.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);
                    System.out.println("accept a connection from " + accept.getRemoteAddress());
                } else if (key.isConnectable()) {
                    System.out.println("isConnectable");
                } else if (key.isReadable()) {
                    SocketChannel sc = (SocketChannel) key.channel();
                    ByteBuffer bb = ByteBuffer.allocate(1024);
                    String msg = "";
//                    sc.register(selector, SelectionKey.OP_WRITE);
                    System.out.println("收到" + sc.getRemoteAddress() + "消息：" + msg);
                } else if (key.isWritable()) {
                    SocketChannel sc = (SocketChannel) key.channel();
//                    sc.register(selector, SelectionKey.OP_READ);
                } else if (key.isValid()) {
                    System.out.println("isValid");
                }
                it.remove();
            }
        }


    }

    private static int getRead(SocketChannel sc) {
        try {
            return sc.read(readBf);
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }
}
